package com.red.wine.ui;

import java.io.IOException;

import com.google.json.Gson;
import com.google.json.JsonParseException;
import com.red.wine.R;
import com.red.wine.WineApp;
import com.red.wine.model.BindData;
import com.red.wine.model.BindReq;
import com.red.wine.model.Headers;
import com.red.wine.model.LoginData;
import com.red.wine.model.LoginReturn;
import com.red.wine.model.RegisterData;
import com.red.wine.model.RegisterReq;
import com.red.wine.model.RegisterReturn;
import com.red.wine.model.SignData;
import com.red.wine.model.SignReq;
import com.red.wine.model.UserInfo;
import com.red.wine.util.IntentUtil;
import com.red.wine.util.PrefsUtils;
import com.red.wine.util.StringUtil;
import com.red.wine.webservice.ServiceAsynTask;
import com.red.wine.webservice.ServiceHelper;
import com.red.wine.webservice.ServiceHost;
import com.tencent.weibo.oauthv1.OAuthV1;
import com.tencent.weibo.oauthv1.OAuthV1Client;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class LoginActivity extends BaseActivity{
//	private EditText name;
//	private EditText pass;
//	private Button signbtn;
//	TextView register, regetpass;
	private ImageView back;
	private Context context;
//	private TextView bindw, bindq;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signa_layouts);
		context = this;
//		bindw = (TextView) findViewById(R.id.login_bysina);
//		bindq = (TextView) findViewById(R.id.login_qq);
		back = (ImageView) findViewById(R.id.taset_top_back_btn_2s);
		back.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				IntentUtil.redirectToNext(context, MainActivity.class);
				finish();
			}
		});
		
//		bindq.setOnClickListener(new OnClickListener() {
//			
//			public void onClick(View v) {
//				try {
//					bindtengxun();
//				} catch (Exception e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//			}
//		});
	}
	
	private String oauthCallback = "http://wine.5do.com/webview/qq/callback.php";
 	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP KEY
 	private String oauthConsumeKey = "801423282";
 	// !!!请根据您的实际情况修改!!! 换为您为自己的应用申请到的APP SECRET
 	private String oauthConsumerSecret = "5761224eb370ab8c70c1bf44894bc69a";
	 //!!!请根据您的实际情况修改!!!      认证成功后浏览器会被重定向到这个url中  必须与注册时填写的一致
    private String redirectUri="http://wine.5do.com/webview/qq/callback.php";                   
    //!!!请根据您的实际情况修改!!!      换为您为自己的应用申请到的APP KEY
    private String clientId = "801423282"; 
    //!!!请根据您的实际情况修改!!!      换为您为自己的应用申请到的APP SECRET
    private String clientSecret="5761224eb370ab8c70c1bf44894bc69a";
    private OAuthV1 oAuth1;  

    private OAuthV2 oAuth;
	
	protected void bindtengxun() throws Exception {
		oAuth1 = new OAuthV1(oauthCallback);
		oAuth1.setOauthConsumerKey(oauthConsumeKey);
		oAuth1.setOauthConsumerSecret(oauthConsumerSecret);

		oAuth1 = OAuthV1Client.requestToken(oAuth1);
		Log.e("TAG","返回nrequest_token:"+oAuth1.getOauthToken()+ "返回request_token_secret:"+oAuth1.getOauthTokenSecret());
		 
		 oAuth1=OAuthV1Client.accessToken(oAuth1);
		 Log.e("接收返回码", "\naccess_token:\n"+oAuth1.getOauthToken()+
					"\naccess_token_secret:\n"+oAuth1.getOauthTokenSecret());
		
		 
		oAuth = new OAuthV2(redirectUri);
		oAuth.setClientId(clientId);
		oAuth.setClientSecret(clientSecret);
		
		  //关闭OAuthV2Client中的默认开启的QHttpClient。
        OAuthV2Client.getQHttpClient().shutdownConnection();
        Intent intent = new Intent(LoginActivity.this, OAuthV2AuthorizeWebView.class);//创建Intent，使用WebView让用户授权
        intent.putExtra("oauth", oAuth);
        startActivityForResult(intent,2);  
	}

	/*
	 * 通过读取OAuthV1AuthorizeWebView返回的Intent，获取用户授权后的验证码
	 */
	protected void onActivityResult(int requestCode, int resultCode, Intent data)	{
		try{
		 if (requestCode==2) {
	            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {
	                oAuth=(OAuthV2) data.getExtras().getSerializable("oauth");
	              
	                if(oAuth.getStatus()==0)
	                    Toast.makeText(getApplicationContext(), "登陆成功", Toast.LENGTH_SHORT).show();
	                	getData("weibo", oAuth.getAccessToken(), oAuth.getRefreshToken(), oAuth.getExpiresIn(), oAuth.getClientId());
	            }
	       }
		}catch(Exception exception){
			exception.printStackTrace();
		}
	}
	
	private void getData(final String type, final String access_token, final String refresh_token, final String expires_in, final String third_id){
		showLoading();
		new ServiceAsynTask<RegisterReturn>() {

			@Override
			protected RegisterReturn callService() throws IOException,
					JsonParseException, AssertionError {
				BindReq taste = new BindReq();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				BindData data = new BindData();
				data.setType(type);
				data.setAccess_token(access_token);
				data.setRefresh_token(refresh_token);
				data.setExpires_in(expires_in);
				data.setThird_id(third_id);

				taste.cmd = "user_bind";
				taste.headers = header;
				taste.data = data;
				taste.sid= "7b8bb3e017b56d612123e564f5594d3006217f";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						RegisterReturn.class);
			}

			@Override
			protected void runWithResult(RegisterReturn result) throws Exception {
				
				if (result != null) {
					bindData(result);
					Log.e("TAG", "isnotnull");
				} else {
					Log.e("TAG", "is null");
					Toast.makeText(context, "发送失败", Toast.LENGTH_SHORT).show();
				}
				hideLoading();
			}

			@Override
			protected void runWithError(RegisterReturn result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常");
				IntentUtil.redirectToNext(context, LoginActivity.class);
				finish();
				hideLoading();
			}
		}.execute();
	}
	
	private void bindData(RegisterReturn result){
		if(result.getRsp().equals("1")){
			Toast.makeText(context, "绑定成功", Toast.LENGTH_SHORT).show();
		}else{
			Toast.makeText(context, "绑定失败", Toast.LENGTH_SHORT).show();
		}
	}
	
	private void getData(final String name, final String pass){
		showLoading();
		new ServiceAsynTask<LoginReturn>() {

			@Override
			protected LoginReturn callService() throws IOException,
					JsonParseException, AssertionError {
				SignReq taste = new SignReq();
				Headers header = new Headers();
				header.setUa("ANDROID_HY/2.0.1.0 (customerid=gypsii, variant=gypsii)");

				SignData data = new SignData();
				data.setName(name);
				data.setPass(pass);

				taste.cmd = "user_login";
				taste.headers = header;
				taste.data = data;
//				taste.sid = "";

				String up = new Gson().toJson(taste);
				String send = StringUtil.unicodeToUtf8("json=" + up);
				String urlstr = ServiceHost.getTasteURL();

				return ServiceHelper.getInstance().postData(urlstr, send,
						LoginReturn.class);
			}

			@Override
			protected void runWithResult(LoginReturn result) throws Exception {
				
				if (result != null) {
					bindData(result, name, pass);
					Log.e("TAG", "isnotnull");
				} else {
					Log.e("TAG", "is null");
					PrefsUtils.setHaseRegister(null);
				}
				
				hideLoading();
			}

			@Override
			protected void runWithError(LoginReturn result, int iErrorCode)
					throws Exception {
				Log.e("TAG", "异常");
				PrefsUtils.setHaseRegister(null);
				hideLoading();
			}
		}.execute();
	}
	
	private LoginData data;
	private UserInfo info;
	private void bindData(LoginReturn result,String name, String pass){
		if(result.getRsp().equals("1")){
			PrefsUtils.setHaseRegister(name);
			PrefsUtils.setFirst("1");
			if(result.getData() != null){
				data = result.getData();
			}
			if(data != null){
				info = data.getInfo();
			}
			if(data.getCon() != null && data.getCon().size() > 0){
				 
			}
			if(info != null){
				if(!StringUtil.isEmptyOrNull(info.getGender())){
					if(info.getGender().equals("F")){
						PrefsUtils.setSex("男");
					}else if(info.getGender().equals("M")){
						PrefsUtils.setSex("女");
					}
				}
				PrefsUtils.setPath(!StringUtil.isEmptyOrNull(info.getThumbnail())?info.getThumbnail():null);
				PrefsUtils.setDyName(!StringUtil.isEmptyOrNull(info.getDisplay_name())?info.getDisplay_name():null);
				PrefsUtils.setCity(!StringUtil.isEmptyOrNull(info.getCity())?info.getCity():null);
			}
			
			Toast.makeText(context, "登陆成功", Toast.LENGTH_SHORT).show();
			PrefsUtils.setName(name);
			PrefsUtils.setPass(pass);
			IntentUtil.redirectToNext(context, MyCenterActivity.class);
			finish();
		}else{
			PrefsUtils.setHaseRegister(null);
			Toast.makeText(context, "登陆失败", Toast.LENGTH_SHORT).show();
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			IntentUtil.redirectToNext(context, MainActivity.class);
			finish();
		}
		return super.onKeyDown(keyCode, event);
	}
}
